﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.IO;
using System.Text.RegularExpressions;
using System.Resources;
using System.Xml;


namespace WpfHardCodedStringsFinder
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public string FilesToSearch
        {
            get { return (string)GetValue(FilestToSearchProperty); }
            set { SetValue(FilestToSearchProperty, value); }
        }

        // Using a DependencyProperty as the backing store for FilestToSearch.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FilestToSearchProperty =
            DependencyProperty.Register("FilesToSearch", typeof(string), typeof(MainWindow), new UIPropertyMetadata(""));

		public string ProjetcRootPath
		{
			get { return (string)GetValue(ProjetcRootPathProperty); }
			set { SetValue(ProjetcRootPathProperty, value); }
		}

		// Using a DependencyProperty as the backing store for ProjetcRootPath.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty ProjetcRootPathProperty =
			DependencyProperty.Register("ProjetcRootPath", typeof(string), typeof(MainWindow), new UIPropertyMetadata(string.Empty));

        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //var prj = Common.VisualStudioHelper.GetProjectsList(@"E:\MyProjects\WpfVkClient\WpfVkontacteClient");
            //var prj = Common.VisualStudioHelper.GetProjectsList(@"D:\My\MyProj\WpfVkontacteClient");

            //var infos = Common.VisualStudioHelper.GetDeatiledProjectInfos(@"E:\MyProjects\WpfHardCodedStringsFinder\WpfHardCodedStringsFinder\WpfHardCodedStringsFinder.csproj");
            //var infos = Common.VisualStudioHelper.GetDeatiledProjectInfos(@"D:\My\MyProj\WpfVkontacteClient\WpfVkontacteClient\WpfVkontacteClient.csproj");
            try
            {
                // Create a instance of ResourceWriter and specify the name of the resource file.
                System.Resources.ResourceWriter RWObj = new ResourceWriter(AppDomain.CurrentDomain.BaseDirectory + "MyResource.resx");

                // Add String resource 
                RWObj.AddResource("FirstName", "Kishor");
                RWObj.AddResource("LastName", "Naik");

                // Close the Resource Writer
                RWObj.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }


            ResourceManager rm = new ResourceManager("Resources", System.Reflection.Assembly.GetExecutingAssembly());
            if (rm != null)
            {
                string dataStr = rm.GetString("searchValue");
                //MessageBox.Show(dataStr);
            }

            using (FileStream read = new FileStream("e:\\cs2.cs", FileMode.Open))
            using (FileStream write = new FileStream("e:\\cs.cs", FileMode.OpenOrCreate))
            {
                byte[] data = new byte[read.Length];
                write.SetLength(0);

                int readed = read.Read(data, 0, data.Length);
                write.Write(data, 0, readed);
                write.Flush();
            }
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            List<Entities.SeachedItem> lines = new List<Entities.SeachedItem>();
            if (!string.IsNullOrEmpty(FilesToSearch) && System.IO.File.Exists(FilesToSearch))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("PatternData.xml");
                XmlNode node = doc.SelectNodes("Patterns/Pattern")[0];
                string pattern = node.SelectSingleNode("Value/text()").Value;

                using (StreamReader sr = new StreamReader(FilesToSearch, Encoding.UTF8))
                {
                    string readLine = string.Empty;
                    StringBuilder sb = new StringBuilder();
                    while ((readLine = sr.ReadLine()) != null)
                    {
                        sb.AppendLine(readLine);
                    }

                    foreach (Match item in Regex.Matches(sb.ToString(), pattern, RegexOptions.Compiled))
                    {
                        Entities.SeachedItem searched = new Entities.SeachedItem();
                        searched.Value = item.Value;
                        searched.BeginIndex = item.Index;
                        searched.EndIndex = searched.BeginIndex + item.Value.Length;
                        searched.FullPath = FilesToSearch;
                        lines.Add(searched);
                    }
                }
                lstStrings.ItemsSource = lines;
            }
        }

        /// <summary>
        /// method for reading a value from a resource file
        /// (.resx file)
        /// </summary>
        /// <param name="file">file to read from</param>
        /// <param name="key">key to get the value for</param>
        /// <returns>a string value</returns>
        private string ReadResourceValue(string file, string key)
        {
            //value for our return value
            string resourceValue = string.Empty;
            try
            {
                // specify your resource file name 
                string resourceFile = file;
                // get the path of your file
                string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
                // create a resource manager for reading from
                //the resx file
                ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null);
                // retrieve the value of the specified key
                resourceValue = resourceManager.GetString(key);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                resourceValue = string.Empty;
            }
            return resourceValue;
        }

        private void btnBeginProcess_Click(object sender, RoutedEventArgs e)
        {
            if (lstStrings.ItemsSource == null)
                return;

            int i = 0;
            foreach (Entities.SeachedItem item in lstStrings.ItemsSource)
            {
                item.RenameValue = string.Format("value{0}", i);
                i++;
            }

            Views.ReplacementWindow repWind = new Views.ReplacementWindow();
            repWind.Owner = this;
			repWind.ProjectRootPath = this.ProjetcRootPath;
            repWind.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            repWind.lstView.ItemsSource = lstStrings.ItemsSource;
            repWind.Show();

        }

    }
}
